var md5 = require('./utils/md5.js');
var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
//app.js
App({
  onLaunch: function (options) {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // console.log('app options');
    // console.log(options);
    // if (options.hasOwnProperty('storeid')) {
    //   console.log('storeid appjs= ' + options.storeid);
    // }

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo;

              console.log(res.userInfo);

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    });

    this.loadToServer();
  },
  globalData: {
    userInfo: null,
    storeInfo:null,
    webUrl: "https://www.jubenxiong.com/games/dianwu/php/index.php/store/",
    ImgwebUrl: "https://www.jubenxiong.com/games/dianwu/admin",
    pageSize: 10
  },
  loadToServer: function (backfun = null) {    
    var uid = wx.getStorageSync('uid');
    if (uid>0){
      var url = this.globalData.webUrl + 'User/userinfo';
      if (backfun == null){
        this.loadDataFromServer(url, this.loadCallBack, {});
      }
      else{
        this.loadDataFromServer(url, backfun, {});
      }
    }
  },
  loadCallBack: function (res) {

    wx.hideToast();

    if (res.status != 'ok') {
      wx.showToast({
        title: '加载中~',
        image: '../../imgs/tips.png'
      });
      return;      
    }

    var awardlist = res.result.award;
    for (var i = 0; i < awardlist.length; i++) {
      awardlist[i].icon = this.globalData.ImgwebUrl + awardlist[i].icon;
    }

    var userinfo = res.result.uinfo;
    userinfo.rolename = this.getUserRole(userinfo.role);
    userinfo.sexname = userinfo.sex == 1 ? '男' : '女';
    userinfo.birthdaystr = this.formatDateTime(userinfo.birthday, false);
    this.globalData.userinfo = userinfo;
    this.globalData.awardlist = awardlist;
  },
  loadUserInfo:function(backfun){
    this.loadToServer(backfun);
  },
  updateList:{

  },
  UpdateList_fun: function (upname,valuse) {
    this.updateList[upname] = valuse;
  },
  getUpdateList(upname){
    return this.updateList[upname];
  },
  getOP: function (res,backfunc=null) {//提交用户信息 获取用户id

    var that = this;
    var userInfo = res;
    var urlStr = that.globalData.webUrl + "User/XcxGetOpenid";
    
    console.log('code2=' + that.globalData.code);

    wx.request({
      url: urlStr,
      data: {
        code: that.globalData.code,
        userInfo: userInfo,
        storeid: that.globalData.storeid
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res && res.header && res.header['Set-Cookie']) {
          wx.setStorageSync('cookieKey', res.header['Set-Cookie']);//保存Cookie到Storage
        }
        if (res && res.data && res.data.result && res.data.result.uid) {
          wx.setStorageSync('uid', res.data.result.uid);//保存Cookie到Storage
        }

        if (res && res.data && res.data.result && res.data.result.nickName) {
          wx.setStorageSync('username', res.data.result.nickName);//保存Cookie到Storage
        }

        if (res && res.data && res.data.result && res.data.result.ukey) {
          wx.setStorageSync('ukey', res.data.result.ukey);//保存Cookie到Storage
        }
        if (res.data.result) {
          var tokenstr = md5.hexMD5(res.data.result.uid + res.data.result.ukey);
          wx.setStorageSync('token', tokenstr);
        }
        console.log('uid:' + res.data.result.uid);
        that.loadToServer(backfunc);
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon:'none'
        });
      }
    })
  },
  loadDataFromServer: function (urlStr, callback, paramsobj = {}) {
    try {
      paramsobj.uid = wx.getStorageSync('uid');
      paramsobj.token = wx.getStorageSync('token');
      paramsobj.storeid = this.globalData.storeid;
    }
    catch (e) {
      wx.showToast({
        title: '参数有误',
        icon: 'none'
      });
      return;
    }
    var header = {
      "Cookie": wx.getStorageSync('cookieKey')
    };
    var that = this;
    wx.request({
      url: urlStr,
      header: header,
      method: 'post',
      data: paramsobj,
      success: function (res) {
        if (res.data.status == '400'){
          wx.setStorageSync('token', '');
        }

        if (res.data.status == '4001') {
          wx.showToast({
            title: "店铺有效期已过",
            image: '../imgs/tips.png',
          });
          return;
        }

        that.callBackCenter(callback, res.data);
      },
      fail: function (res) {
        that.callBackCenter(callback, "err");
      }
    });
  },
  callBackCenter: function (callback, data) {
    callback(data);
  },
  appShowLoading: function (duration) {
    wx.showToast({
      title: '',
      icon: 'loading',
      duration: duration
    });
  },
  repicSrc: function (str) {
    str = str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
    //思路分两步：作者（yanue）.
    //1，匹配出图片img标签（即匹配出所有图片），过滤其他不需要的字符
    //2.从匹配出来的结果（img标签中）循环匹配出图片地址（即src属性）
    if (str == "" || str == null)
      return;
    //匹配图片（g表示匹配所有结果i表示区分大小写）
    var imgReg = /<img.*?(?:>|\/>)/gi;
    //匹配src属性
    var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    var arr = str.match(imgReg);
    if (arr == null)
      return;

    var keyArr = {};
    var i = 0;
    var src = '';
    for (i = 0; i < arr.length; i++) {
      src = arr[i].match(srcReg);
      if (src[1]) {
        keyArr[src[1]] = true;
      }

    }
    var imgArr = [];
    var tmpstr = '';
    for (i = 0; i < arr.length; i++) {
      src = arr[i].match(srcReg);
      if (src[0].indexOf('https') < 0 && src[0].indexOf('http') < 0) {
        tmpstr = app.globalData.ImgwebUrl + src[0];
      }
      else {
        tmpstr = src[0];
      }
      tmpstr = tmpstr.replace(/src="/g, '');
      tmpstr = tmpstr.replace(/"/g, '');
      imgArr.push(tmpstr);
    }
    return imgArr;
  },
  formatDateTime: function (timeStamp, longflag = true) {
    var date = new Date();
    date.setTime(timeStamp * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    if (longflag == false) {
      return y + '-' + m + '-' + d;
    }
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  },
  getUserRole: function (role) {
    if (role == 1) {
      return '客户';
    }
    else if (role == 2) {
      return '商户';
    }
  },
  getStoreName(){
    if (!this.globalData || !this.globalData.storeInfo || !this.globalData.storeInfo.name){
      return '爱梨精选';
    }
    return this.globalData.storeInfo.name;
  },
  getShareObj(){
    var shareObj = {
      title: this.getStoreName(),        // 默认是小程序的名称(可以写slogan等)
      path: '/pages/index/index?storeid=' + this.globalData.storeid,        // 默认是当前页面，必须是以‘/’开头的整路径
      imgUrl: '',     //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    };
    return shareObj;
  },
  checkLogin: function (backfunc = null) {
    var that = this;
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.globalData.code = res.code;
        wx.setStorageSync('code', res.code);
        console.log('code=' + res.code);
        that.getOP(null, backfunc);
      },
      fail: function () {
        wx.showToast({
          title: '系统提示:网络错误',
          icon: 'warn',
          duration: 1500,
        })
      }
    });
  },

})